<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--      <el-card class="box-card">-->
      <!-- 查询表单 -->
      <content-block>
        <el-form :inline="true" :model="queryForm" class="demo-form-inline">
          <el-form-item label="人员编号">
            <person-rpc ref="personRpc" @personRpcCallBack="personRpcCallBack" />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="queryForm.aac003" placeholder="请输入姓名" :disabled="true" />
          </el-form-item>

          <el-form-item label="业务类型" prop="aaa121">
            <el-select v-model="queryForm.aaa121" placeholder="请选择" filterable allow-create>
              <el-option
                v-for="item in filteredOptions"
                :key="item.id"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button type="primary" @click="showAddDialog">新增电子材料</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </content-block>
      <!--表格渲染-->
      <content-block>
        <el-alert
          v-if="true"
          title="温馨提示"
          type="info"
          description="双击查看材料明细"
          show-icon
        />
        <el-table ref="table" v-loading="crud.loading" :height="550" :data="crud.data" size="small" style="width: 100%;" border :header-cell-style="{background:'#f5f7fa', color:'#777'}" @row-dblclick="handlePreview">
          <el-table-column type="index" label="序号" width="50" align="center" header-align="center" fixed="left" />
          <el-table-column prop="aac001" label="个人编号" fixed="left" width="220px" align="center" header-align="center" />
          <el-table-column prop="aac003" label="姓名" width="150px" align="center" header-align="center" />
          <el-table-column prop="aaa121" label="业务类型" width="250px" align="center" header-align="center" :formatter="formatter" />
          <el-table-column prop="id" label="材料编号" width="220px" align="center" header-align="center" />
          <el-table-column prop="name" label="材料名称" width="300px" align="center" header-align="center" show-overflow-tooltip />
          <el-table-column prop="filenum" label="文件数" width="150px" align="center" header-align="center" />
          <el-table-column prop="aae036" label="创建时间" width="200px" align="center" header-align="center" />
          <el-table-column
            label="操作"
            width="100"
            fixed="right"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handlePreview(scope.row)"
              >查看</el-button>
              <!--              <el-button-->
              <!--                size="mini"-->
              <!--                type="danger"-->
              <!--                @click="handleDelete(scope.row)"-->
              <!--              >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </content-block>
      <!-- 材料明细对话框 -->
      <file-detail
        ref="fileDetail"
        :visible.sync="seeDetailVisible"
        :current-material-hz="currentMaterial"
        @gbCallBack="gbCallBack"
      />
      <!--      </el-card>-->
      <!-- 新增材料对话框 -->
      <material-add-dialog
        :id="id"
        :visible.sync="addDialogVisible"
        :person-list="personList"
        :business-type-options="businessTypeOptions"
        append-to-body
        @gbCallBack="gbCallBack"
        @uploadSuccessBack="uploadSuccessBack"
        @refresh="handleRefresh"
      />
      <!-- 预览对话框 -->
      <!--      <material-preview-dialog-->
      <!--        :visible.sync="previewDialogVisible"-->
      <!--        :material="currentMaterial"-->
      <!--        @gbCallBack="gbCallBack"-->
      <!--      />-->
    </div>
  </div>
</template>

<script>
import MaterialAddDialog from './MaterialAddDialog'
// import MaterialPreviewDialog from './MaterialPreviewDialog'
import ContentBlock from '@/components/labers/contentBlock'
import CRUD, { crud, header, presenter } from '@crud/crud'
import fileUpload from '@/views/ynsb_comm/fileupload/fileUpload'
import pagination from '@crud/Pagination'
import PersonRpc from '@/views/ynsb_comm/comm/module/personRpc'
import moment from 'moment'
import FileDetail from '@/views/ynsb_comm/fileupload/FileDetail'
import fileupload from '@/views/ynsb_comm/fileupload/fileUpload'
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'MaterialManagement',
  components: {
    FileDetail,
    PersonRpc,
    ContentBlock,
    MaterialAddDialog,
    pagination
    // MaterialPreviewDialog
  },
  mixins: [presenter(), header(), crud()],
  cruds() {
    return CRUD({ title: '电子材料录入', url: '/api/electronic-material/list', idField: 'id', sort: 'id,desc', crudMethod: { ...fileUpload }})
  },
  // 数据字典
  dicts: ['aaa121'],
  data() {
    return {
      queryForm: {
        aac001: '',
        aac003: '',
        aaa121: ''
      },
      materialList: [],
      personList: [
      ],
      businessTypeOptions: [
      ],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      addDialogVisible: false,
      previewDialogVisible: false,
      seeDetailVisible: false,
      id: '',
      currentMaterial: null
    }
  },
  computed: {
    filteredOptions() {
      // 在这里定义您的过滤条件
      return this.dict.aaa121.filter(item =>
        item.value === '040101' || item.value === '040102' || item.value === '030101'
      )
    }
  },
  created() {
  },
  methods: {
    moment,
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    personRpcCallBack(item) {
      this.queryForm.aac001 = item.aac001
      this.queryForm.aac003 = item.aac003
    },
    // 查询材料列表
    fetchMaterialList() {
      this.crud.params = {
        aac001: this.queryForm.aac001,
        queryType: '0',
        aaa121: this.queryForm.aaa121
      }
      this.crud.pageChangeHandler(1)
    },
    // 处理查询
    handleQuery() {
      this.previewDialogVisible = false
      this.addDialogVisible = false
      this.fetchMaterialList()
    },

    // 重置查询
    resetQuery() {
      this.queryForm = {
        aac001: '',
        aaa121: ''
      }
      this.$refs.personRpc.restAac001('')
      this.handleQuery()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchMaterialList()
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该材料, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        try {
          fileupload.deleteFile({ ...row }).then(res => {
            this.$message.success('材料删除成功!')
            this.fetchMaterialList()
          })
        } catch (error) {
          // 4. 错误处理
          this.$message.error(`删除失败: ${error.message || '未知错误'}`)
        }
      }).catch(() => {
        // 用户点击取消
        this.$message({
          type: 'info',
          message: '已取消删除',
          duration: 1000
        })
      })
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchMaterialList()
    },

    // 显示新增对话框
    showAddDialog() {
      this.id = uuidv4()
      this.addDialogVisible = true
    },

    // 预览材料
    handlePreview(row) {
      this.currentMaterial = row
      setTimeout(() => {
        this.seeDetailVisible = true
        this.$refs.fileDetail.getFileDetail()
      }, 500) // 延迟1秒后显示弹窗
      // row.aae036_yw = moment(row.aae036).format('YYYY-MM-DD')
      // // 查询图片base64
      // // 假设查询的数据
      // fileupload.getBase64({ ...row }).then(res => {
      //   this.currentMaterial.base64 = res
      //   this.previewDialogVisible = true
      // })
    },

    // 刷新列表
    handleRefresh() {
      this.id = ''
      this.fetchMaterialList()
    },
    // 关闭新增
    gbCallBack() {
      this.previewDialogVisible = false
      this.addDialogVisible = false
      this.seeDetailVisible = false
    },
    // 预览打开后关闭详情弹窗
    ylCallBack() {
      this.seeDetailVisible = false
    },
    uploadSuccessBack() {
      this.addDialogVisible = false
      this.fetchMaterialList()
    },
    formatter(row, column, cellValue) {
      // 根据 aae140 的值进行转码
      const key = column.property
      const data = this.dict[key]
      if (data.length === 0) {
        return cellValue
      }
      const dataList = data.filter(item => item.value === cellValue)
      console.log(dataList, 'data')
      if (dataList !== null && dataList !== [] && dataList !== undefined && dataList.length > 0) {
        return dataList[0].label
      } else {
        return cellValue
      }
    }
  }
}
</script>

<style scoped>
.material-management {
  padding: 20px;
}

.box-card {
  max-width: 1200px;
  margin: 0 auto;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
